package com.ww.springboot.boot.algorithm.leetcode1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 * -----> 最长公共子序列
 *
 *
 * @author 🧑 ‍wanwei
 * @since 2022-11-09 16:45
 */
public class CN两个字符串的删除操作 {

    public static void main(String[] args) {

        System.out.println(minDistance("intention", "execution"));
    }

    public static int minDistance(String word1, String word2) {
        int length = getCommon(word1, word2);
        int length2 = getCommon(word2, word1);

        System.out.println(length);
        System.out.println(length2);

        if (length2 > length) {
            length = length2;
        }

        return (word1.length() - length) + (word2.length() - length);
    }

    /**
     * 获取共同的元素
     * 1.记录B中每个字符 在A中的最左边的坐标(需要考虑重复字符的问题)
     * 2.从记录中找到可以连续的最长字符串
     * 此解法太复杂 太多场景要考虑且重复遍历率太高
     * 第一步应该是对的
     * 第二步该怎么改进？？？？
     *
     * @param word1
     * @param word2
     * @return
     */
    public static int getCommon(String word1, String word2) {

        //坐标
        Map<Character, List<Integer>> map = new HashMap<>();
        //字符使用次数
        Map<Character, Integer> mapTimes = new HashMap<>();

        for (int i = 0; i < word1.length(); i++) {
            List<Integer> list = map.getOrDefault(word1.charAt(i), new ArrayList<>());
            list.add(i);
            map.put(word1.charAt(i),list);
        }

        int[] indexArray = new int[word2.length()];

        int lengthMax = 0;
        int length = 0;
        int last = -1;

        for (int i = 0; i < word2.length(); i++) {
            List<Integer> list = map.getOrDefault(word2.charAt(i),new ArrayList<>());
            Integer times = mapTimes.getOrDefault(word2.charAt(i),0);
            int index = -1;
            if(list.size() > times){
                index = list.get(times);
            }
            indexArray[i] = index;
            mapTimes.put(word2.charAt(i),++times);

            if (indexArray[i] != -1 && last == -1) {
                length = 1;
                last = i;
            } else {
                if (indexArray[i] != -1 && last != -1) {
                    //比较上一个坐标与当前坐标值的大小
                    if (indexArray[i] > indexArray[last]) {
                        last = i;
                        length++;
                    } else {
                        if (length > lengthMax) {
                            lengthMax = length;
                        }
                        last = i;
                        length = 1;
                    }
                }

            }
        }
        if (length > lengthMax) {
            lengthMax = length;
        }
        return lengthMax;
    }
}
